package com.magee.router.router_runtime

import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.util.Log
import java.net.URI

object Router {
    private const val TAG = "RouterTAG"
    private const val GENERATED_MAPPING = "com.imooc.router.mapping.generated.RouterMapping"

    private val mapping: HashMap<String, String> = HashMap()

    fun init() {
        val clazz = Class.forName(GENERATED_MAPPING)
        val method = clazz.getMethod("get")
        val allMapping = method.invoke(null) as Map<String, String>
        if (allMapping?.size > 0) {
            mapping.putAll(allMapping)
            Log.d(TAG, "init get  allMapping size =${allMapping?.size}")
            allMapping.forEach {
                Log.d(TAG, "key=${it.key},value=${it.value}")
            }
        }
    }

    fun go(context: Context, url: String) {
        if (context == null || url == null) {
            Log.d(TAG, "fun go context==null||url==null ")
            return
        }
        var uri = Uri.parse(url)
        val scheme = uri.scheme
        val host = uri.host
        val path = uri.path
        var targetActivity = ""
        mapping.onEach {
            var ruri = Uri.parse(it.key)
            val rscheme = ruri.scheme
            val rhost = ruri.host
            val rpath = ruri.path

            if (rscheme == scheme && rhost == host && path == rpath) {
                targetActivity = it.value
            }
        }

        if (targetActivity == "") {
            Log.d(TAG, "fun go targetActivity==null")
            return
        }
        val bundle = Bundle()
        val query = uri.query
        query?.let {
            if (it.length >= 3) {
                val args = it.split("&")
                args.onEach { arg ->
                    val splits = arg.split("=")
                    bundle.putString(splits[0],splits[1])
                }
            }
        }
        val clazz=Class.forName(targetActivity)
        val intent=Intent(context,clazz)
        intent.putExtras(bundle)
        context.startActivity(intent)
    }
}